<?php defined('SYSPATH') or die('No direct script access.');

class Model_Coupon extends ORM
{ 
    const COUPONS_PER_PAGE = 10; 
    protected $_reload_on_wakeup = false;
    
    public function get_coupons($category = null, $type = null, $shop = null, $page = null, $count = false)
    {        
        $category_id = $category;
        if ($category instanceof Model_Category) {
            $category_id = $category->id;
        }
        
        $type_id = $type;
        if ($type instanceof Model_Type) {
            $type_id = $type->id;    
        }
        
        $shop_id = $shop;
        if ($shop instanceof Model_Shop) {
            $shop_id = $shop->id;    
        }
        
        if ($coupons = Cache::instance()->get('coupons_'.$category_id.'_'.$type_id.'_'.$shop_id.'_'.$page.'_'.$count)) {
            return $coupons;
        }
         
        $query = ORM::factory('coupon'); 
        
        if ($category_id) {
            // TODO
            //$query->where('category_id', '=', $category_id);
        }
        
        if ($type_id) {
            // TODO
            //$query->where('brand_id', '=', $type_id); 
        }
        
        if ($shop_id) {
            $query->where('shop_id', '=', $shop_id);    
        }
        
        $date = new DateTime();
        $query->where('end_date', '>', $date->format('Y-m-d H:i:s'));
        
        if ($count) {
            $result = $query->count_all();
            Cache::instance()->set('coupons_'.$category_id.'_'.$type_id.'_'.$shop_id.'_'.$page.'_'.$count, $result);
            return $result;
        } 
        
        $query->order_by('start_date', 'DESC');      
            
        if ($page) {
            $count = self::get_coupons_per_page();
            $offset = ($page - 1) * $count;
            $query->offset($offset)->limit($count);    
        }
        
        $coupons = $query->find_all()->as_array();  
        Cache::instance()->set('coupons_'.$category_id.'_'.$type_id.'_'.$shop_id.'_'.$page.'_'.$count, $coupons); 
        return $coupons;
    } 
    
    public static function get_coupons_per_page()
    {
        return self::COUPONS_PER_PAGE;
    }
    
    public function get_url()
    {
        if (isset($_COOKIE['subid']) && ($subid = $_COOKIE['subid'])) {
            if (strstr($this->gotolink, 'actionpay.ru') !== false) {
                return str_replace('/subaccount/', '/'.$subid.'/', $this->gotolink);
            }
            if (strstr($this->gotolink, 'admitad.com') !== false) {        
                //return str_replace('/?ulp=', '/subid/'.$subid.'/?ulp=', $this->url);
                return $this->gotolink.'?subid='.$subid;
            }
            if (strstr($this->gotolink, 'cpl1.ru') !== false) {
                return str_replace('/subaccount', '/'.$subid, $this->gotolink);
            }
        }    
        return $this->gotolink;    
    }
    
}